import os
import sys

from langchain_openai import ChatOpenAI
from langchain.agents import AgentExecutor, create_tool_calling_agent
from langchain_community.tools.tavily_search import TavilySearchResults
from langchain_core.prompts import ChatPromptTemplate

# 添加项目根目录到Python路径
sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))

# 导入配置读取器
from config_reader import get_tavily_api_key, get_langsmith_config

# 从配置文件获取API密钥
try:
    tavily_api_key = get_tavily_api_key()
    langsmith_config = get_langsmith_config()
    
    # 设置环境变量
    os.environ["TAVILY_API_KEY"] = tavily_api_key
    os.environ["LANGCHAIN_TRACING_V2"] = langsmith_config['tracing_v2']
    os.environ["LANGCHAIN_PROJECT"] = langsmith_config['project']
    if langsmith_config['api_key']:
        os.environ["LANGCHAIN_API_KEY"] = langsmith_config['api_key']
        
except Exception as e:
    print(f"配置错误：{e}")
    exit(1)

llm = ChatOpenAI(model="gpt-4o-mini")
tools = [TavilySearchResults(max_results=1)]
prompt = ChatPromptTemplate.from_messages(
    [
        (
            "system",
            "你是一位得力的助手。",
        ),
        ("placeholder", "{chat_history}"),
        ("human", "{input}"),
        ("placeholder", "{agent_scratchpad}"),
    ]
)
# 构建工具代理
agent = create_tool_calling_agent(llm, tools, prompt)
# 通过传入代理和工具来创建代理执行器
agent_executor = AgentExecutor(agent=agent, tools=tools)
response = agent_executor.invoke(
    {"input": "谁执导了2023年的电影《奥本海默》，他多少岁了？"}
)
print(response)
